﻿using WebApi.Models;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;

namespace WebApi.Services
{
    public class BaseService<T> where T : BaseModel
    {
        private readonly IMongoCollection<T> Collection;

        public BaseService(IWebApiDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            var CollectionName = typeof(T).Name + "CollectionName";
            Collection = database.GetCollection<T>(
                settings
                .GetType()
                .GetProperty("CategoryCollectionName")
                .GetValue(settings, null)
                .ToString()
                );
            //Collection = database.GetCollection<T>(settings.CategoryCollectionName);
        }

        public List<T> Get() =>
            Collection.Find(book => true).ToList();

        public T Get(string id) =>
            Collection.Find<T>(book => book.Id == id).FirstOrDefault();

        public T Create(T book)
        {
            Collection.InsertOne(book);
            return book;
        }

        public void Update(string id, T model) =>
            Collection.ReplaceOne(model => model.Id == id, model);

        public void Remove(T model) =>
            Collection.DeleteOne(model => model.Id == model.Id);

        public void Remove(string id) =>
            Collection.DeleteOne(model => model.Id == id);
    }
}